package edison.jcr;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.jcr.Binary;
import javax.jcr.RepositoryException;

public class BinaryImpl implements Binary {

	private byte[] data;
	private boolean disopsed;

	public BinaryImpl(InputStream in) throws IOException {
		this(input2byte(in));
	}

	public BinaryImpl(byte[] data) {
		this.data = data;
		this.disopsed = false;
	}

	public void dispose() {
		data = null;
		disopsed = true;
	}

	public long getSize() throws RepositoryException {
		if (disopsed)
			throw new IllegalStateException();

		return data.length;
	}

	public InputStream getStream() throws RepositoryException {
		if (disopsed)
			throw new IllegalStateException();

		return new ByteArrayInputStream(data);
	}

	private static byte[] input2byte(InputStream inStream) throws IOException {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = inStream.read(buff, 0, 100)) > 0) {
			swapStream.write(buff, 0, rc);
		}

		return swapStream.toByteArray();
	}

	public int read(byte[] b, long position) throws IOException, RepositoryException {
		InputStream in = getStream();
		try {
			long skip = position;
			while (skip > 0) {
				long skipped = in.skip(skip);
				if (skipped <= 0) {
					return -1;
				}
				skip -= skipped;
			}
			return in.read(b);
		} finally {
			in.close();
		}
	}

	@Override
	public String toString() {
		return new String(data);
	}

}